package com.sfhk.service.impl;

import com.sfhk.dao.UserDao;
import com.sfhk.dao.impl.UserDaoImpl;
import com.sfhk.domain.User;
import com.sfhk.service.UserService;
import com.sfhk.utils.LoginException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public void deleteUser(int id) {
        userDao.deleteById(id);
    }

    @Override
    public void addUser(User user) {
        userDao.addUser(user);
    }

    @Override
    public List<User> queryUser() {
        List<User> list = userDao.findAll();
        return list;
    }

    @Override
    public User showUserById(int id) {
        return userDao.findById(id);
    }


    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public void deleteSelectUser(String[] ids) {
        if (ids != null && ids.length > 0){
            for (String id : ids){
                userDao.deleteById(Integer.parseInt(id));
            }
        }
    }

    @Override
    public User login(String username, String password) throws LoginException {
        try {
            User loginUser = userDao.findByUserName(username);
            if (loginUser.getPassword().equals(password)){
                return loginUser;
            }else {
                throw new LoginException("密码错误");
            }
        }catch (EmptyResultDataAccessException e){
            throw new LoginException("用户名错误");
        }
    }

    @Override
    public List<User> queryUserByCategory(String cid) {

        return null;
    }
}
